package org.pentaho.di.core.database.util;

import cn.hutool.core.map.MapUtil;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ConcurrentHashMap;
/**
 * HikariCP连接池
 *
 * @author zg
 * @version 1.0
 * @date 2021/7/7 10:52
 */
@Slf4j
public class HikariCPConnectionPool {

    public static ConcurrentHashMap<String,HikariDataSource> HiKariDataSourceMap= MapUtil.newConcurrentHashMap();

    private static HikariCPConnectionPool INSTANCE = null;

    public static HikariCPConnectionPool getInstance() {

        if (INSTANCE == null) {
            synchronized (HikariCPConnectionPool.class) {
                if (INSTANCE == null) {
                    INSTANCE = new HikariCPConnectionPool();
                }
            }
        }
        return INSTANCE;
    }

    /**
     * 获取数据源根据数据库连接元数据
     * @param userName 用户名
     * @param password 密码
     * @param jdbcUrl jdbc连接字符串
     * @param driverName 驱动名称
     * @return 数据源对象
     */
    public synchronized HikariDataSource getDataSourceByHikari(String userName, String password, String jdbcUrl, String driverName
    ,Integer minimumIdle,Integer maximumPoolSize,Long timeout) {
        String key_name=userName+"_"+password+"_"+jdbcUrl+"_"+driverName;
        if(HiKariDataSourceMap.containsKey(key_name))
        {
            return HiKariDataSourceMap.get(key_name);
        }else {
            HikariDataSource ds = null;
            HikariConfig config = new HikariConfig();
            config.setJdbcUrl(jdbcUrl);
            config.setUsername(userName);
            config.setPassword(password);
            if(minimumIdle!=null) {
                config.setMinimumIdle(minimumIdle);
            }else {
                config.setMinimumIdle(5);
            }if(maximumPoolSize!=null)
            {
                config.setMaximumPoolSize(maximumPoolSize);
            }else {
                config.setMaximumPoolSize(10);
            }
            if(timeout!=null)
            {
                config.setConnectionTimeout(timeout);
            }else {
                config.setConnectionTimeout(30 * 1000L);
            }
            config.setDriverClassName(driverName);
            try {
                ds = new HikariDataSource(config);
                HiKariDataSourceMap.put(key_name, ds);
            } catch (Exception ex) {
            }
            return ds;
        }
    }

}

